#include "serversocket.h"
#include "ui_serversocket.h"

#include <QFileDialog>

ServerSocket::ServerSocket(QTcpSocket *socket, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerSocket)
{
    ui->setupUi(this);

    m_tcpBlockSize = 0;
    m_tcpSocket = socket;

    connect(m_tcpSocket, SIGNAL(readyRead()),
            this, SLOT(readyToRead()));
}

ServerSocket::~ServerSocket()
{
    delete ui;
}

void ServerSocket::readyToRead(void)
{
    QDataStream in(m_tcpSocket);
    in.setVersion(QDataStream::Qt_4_6);

    if(m_tcpBlockSize == 0)
    {
        if(m_tcpSocket->bytesAvailable()<sizeof(quint16))
            return;

        in >> m_tcpBlockSize;
    }

    if(m_tcpSocket->bytesAvailable() < m_tcpBlockSize)
        return;

    QString greeting;
    in >> greeting;
    ui->le_message->setText(greeting);
    m_tcpBlockSize = 0;
}

void ServerSocket::on_pb_send_clicked()
{
    QByteArray buffer;
    QDataStream out(&buffer, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);

//    QString greeting = QString("Hello! The time is %1")
//        .arg(QTime::currentTime().toString());
    out << (quint16)0;
    out << ui->le_message->text();
    out.device()->seek(0);
    out << (quint16)(buffer.size() - sizeof(quint16));

    m_tcpSocket->write(buffer);
}

void ServerSocket::on_toolButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
          tr("Open Image"), "../", tr("Image Files (*.png *.jpg *.bmp)"));

    QImage img(fileName);
    ui->label->setPixmap(QPixmap::fromImage(img));

    QByteArray buffer;
    QDataStream out(&buffer, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);

    out << (quint16)0;
    out << img;
    out.device()->seek(0);
    out << (quint16)(buffer.size() - sizeof(quint16));

    qDebug() << "SendImage: " << buffer.size();
    m_tcpSocket->write(buffer);
}
